package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.L1DatabaseFactory;

import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.utils.SQLUtil;

public class LevelUpRewardTable {

	private static Logger _log = Logger.getLogger(LevelUpRewardTable.class
			.getName());

	private static LevelUpRewardTable _instance = new LevelUpRewardTable();

	public static LevelUpRewardTable getInstance() {
		return _instance;
	}

	private Set<Reward> _rewards = new HashSet<Reward>();

	private LevelUpRewardTable() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {

			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("SELECT * FROM x_levelup_reward");
			rs = pstm.executeQuery();
			while (rs.next()) {
				Reward r = new Reward();
				r.level = rs.getInt("level");
				r.eLevel = rs.getInt("extend_level");
				r.item_id = rs.getInt("item_Id");
				r.count = rs.getInt("count");
				r.crown = rs.getBoolean("crown");
				r.knight = rs.getBoolean("knight");
				r.elf = rs.getBoolean("elf");
				r.dark_elf = rs.getBoolean("dark_elf");
				r.wizard = rs.getBoolean("wizard");
				r.dragon_knight = rs.getBoolean("dragon_knight");
				r.illusionist = rs.getBoolean("illusionist");
				_rewards.add(r);
			}
		} catch (SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public void checkReward(L1PcInstance pc) {
		if (pc.getLevel() > pc.getHighLevel()) {
			for (int i = pc.getHighLevel() + 1; i <= pc.getLevel(); i++) {
				for (Reward r : _rewards) {
					if (r.level == i && r.eLevel == pc.getExtendLevel()) {
						if ((r.crown && pc.isCrown())
								|| (r.knight && pc.isKnight())
								|| (r.elf && pc.isElf())
								|| (r.wizard && pc.isWizard())
								|| (r.dark_elf && pc.isDarkelf())
								|| (r.dragon_knight && pc.isDragonKnight())
								|| (r.illusionist && pc.isIllusionist())) {
							pc.getItem(r.item_id, r.count, 1, "轉生獎勵");
						}
					}
				}
			}

		}
	}

	class Reward {
		int level;
		int eLevel;
		int item_id;
		int count;
		boolean crown;
		boolean knight;
		boolean elf;
		boolean dark_elf;
		boolean wizard;
		boolean dragon_knight;
		boolean illusionist;
	}
}
